import axios from 'axios';

// create an axios instance
const myRequest = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
})

// request interceptor
myRequest.interceptors.request.use(
  config => {
    // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    // config.headers['token'] = '123456'
    return config
  },
  error => {
    console.log(`request 拦截器 error = `, error)
    return Promise.reject(error)
  }
)

// response interceptor
myRequest.interceptors.response.use(
  response => {
    if (response.status !== 200) throw new Error('Network Error')
    if (response.data.code !== 200) throw new Error(JSON.stringify(response.data))
    return response.data
  },
  error => {
    throw error
  }
)

export default myRequest